//jqGrid的配置信息
$.jgrid.defaults.width = 1000;
$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

//工具集合Tools
window.T = {};

// 获取请求参数
// 使用示例
// location.href = http://localhost/index.html?id=123
// T.p('id') --> 123;
var url = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
};
T.p = url;

//请求前缀
//var baseURL = "http://demo.open.renren.io/renren-fast/";
//var baseURL = "/renren-fast/";
var baseURL = "/";

//登录token
var token = localStorage.getItem("token");
if (token == 'null') {
    parent.location.href = baseURL + 'login.html';
}

//jquery全局配置
$.ajaxSetup({
    dataType: "json",
    cache: false,
    headers: {
        "token": token
    },
    complete: function (xhr) {

        //token过期，则跳转到登录页面
        if (xhr.responseJSON.code == 401) {
            parent.location.href = baseURL + 'login.html';
        }
    }
});

//jqgrid全局配置
$.extend($.jgrid.defaults, {
    ajaxGridOptions: {
        headers: {
            "token": token
        }
    }
});

//权限判断
function hasPermission(permission) {

    if (window.parent.permissions.indexOf(permission) > -1) {
        return true;
    } else {
        return false;
    }
}

//重写alert
window.alert = function (msg, callback) {
    parent.layer.alert(msg, function (index) {
        parent.layer.close(index);
        if (typeof(callback) === "function") {
            callback("ok");
        }
    });
}

//重写confirm式样框
window.confirm = function (msg, callback) {
    parent.layer.confirm(msg, {btn: ['确定', '取消']},
        function () {//确定事件
            if (typeof(callback) === "function") {
                callback("ok");
            }
        });
}

//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        alert("请选择一条记录");
        return;
    }

    var selectedIDs = grid.getGridParam("selarrrow");
    if (selectedIDs.length > 1) {
        alert("只能选择一条记录");
        return;
    }

    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        alert("请选择一条记录");
        return;
    }

    return grid.getGridParam("selarrrow");
}

//选择一条记录
function getSelectedRowType() {
    var grid = $("#jqGridType");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        alert("请选择一条记录");
        return;
    }

    var selectedIDs = grid.getGridParam("selarrrow");
    if (selectedIDs.length > 1) {
        alert("只能选择一条记录");
        return;
    }

    return selectedIDs[0];
}

//选择多条记录
function getSelectedRowsType() {
    var grid = $("#jqGridType");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        alert("请选择一条记录");
        return;
    }

    return grid.getGridParam("selarrrow");
}

//---------------------------------------------------------------------------------------------------------------

(function ($) {
    /*
     *  jquery中各个事件执行顺序如下：
     1.ajaxStart(全局事件)
     2.beforeSend
     3.ajaxSend(全局事件)
     4.success
     5.ajaxSuccess(全局事件)
     6.error
     7.ajaxError (全局事件)
     8.complete
     9.ajaxComplete(全局事件)
     10.ajaxStop(全局事件)
     */
    $(document).ajaxStart(onStart)
        .ajaxSend(onSend)
        .ajaxSuccess(onSuccess)
        .ajaxError(onError)
        .ajaxComplete(onComplete)
        .ajaxStop(onStop);

    function onStart(event) {
        //console.log("onStart"," | ",event);

        var index = top.layer.load(0, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
    }

    function onSend(event, xhr, options) {
        //console.log("onSend"," | ",event," | ",xhr," | ",options);
    }

    function onSuccess(event, xhr, options) {
        //console.log("onSuccess"," | ",event," | ",xhr," | ",options);
        //关闭所有弹框防止重叠
        //layer.closeAll();
        //top.layer.closeAll();
        top.layer.closeAll('loading');
    }

    function onError(event, xhr, options, exc) {
        //console.log("onError"," | ",event," | ",xhr," | ",options," | ",exc);
        //关闭所有弹框防止重叠
        //layer.closeAll();
        //top.layer.closeAll();

        //未授权
        if (xhr.status == 401) {
            var msg = "对不起，请求未授权 状态码：" + xhr.status;
            var url = getContextPath();
            if (xhr.responseText) {
                msg = xhr.responseText;
            }
            top.layer.alert(msg, {closeBtn: false}, function () {
                top.location.href = url;
            });
        }
        //强制踢出登录
        else if (xhr.status == 901) {
            var msg = "对不起，您被踢出登录 状态码：" + xhr.status;
            var url = getContextPath();
            if (xhr.responseText) {
                var json = JSON.parse(xhr.responseText);
                if (json.msg) {
                    msg = json.msg;
                }
                if (json.url) {
                    url = getContextPath() + json.url;
                }
            }
            top.layer.alert(msg, {closeBtn: false}, function () {
                top.location.href = url;
            });
        } else {
            var msg = "对不起，系统异常 状态码：" + xhr.status;
            if (exc == "timeout") {
                msg = "对不起，请求超时";
            }

            if (xhr.responseText) {
                msg = xhr.responseText;
            }
            top.layer.alert(msg + "-----" + (xhr.responseText));
        }
    }

    function onComplete(event, xhr, options) {
        //console.log("onComplete"," | ",event," | ",xhr," | ",options);
        top.layer.closeAll('loading');
    }

    function onStop(event) {
        //console.log("onStop"," | ",event);
        top.layer.closeAll('loading');
    }

    /**
     * 获取ContextPath
     */
    function getContextPath() {
        return baseURL; // see taglib.jsp
    }

    /**
     * 将表单转化为json对象
     */
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };


    $.fn.initAreaSelect = function () {
        // 循环，兼容数组对象的情况
        this.each(function () {
            $(this).find("select").each(function (i, item) {
                if (i == 0) {
                    reloadAreaByPArea($(item));
                } else {
                    reloadAreaByPArea($(item), $(item).prev());
                }
            });
        });
    }

    /**
     * 自定义公共验证方法
     * author shuliangxing 2017-5-9 14:25:23
     */
    if (jQuery.validator) {
        // 校验手机号码
        jQuery.validator.addMethod("checkMobile", function (value, element) {
            var length = value.length;
            var regExp = /^1[3,4,5,7,8][0-9]\d{8}$/;
            return this.optional(element) || (length == 11 && regExp.test(value));
        }, "请填写正确的手机号码");

        // 校验身份证
        jQuery.validator.addMethod("checkIdCard", function (value, element) {
            var regExp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            return this.optional(element) || (regExp.test(value));
        }, "请填写正确的身份证号码");

        // 校验银行卡号
        var checkBankCardRetult = "校验银行卡号失败";
        jQuery.validator.addMethod("checkBankCard", function (value, element) {
            checkBankCardRetult = checkBankCardLuhn(value);
            if (checkBankCardRetult === true) {
                return true;
            }
            return false;
        }, function () {
            return checkBankCardRetult
        });

        //异步验证后台用户手机号码是否重复, 使用方法:<input class="required checkMobile" maxlength="11" checkMobileExist="${user.useId }" name="a" />
        //其中${user.useId }填对应的用户id，用来在修改手机号码校验重复时排除当前用户id
        jQuery.validator.addMethod("checkMobileExist", function (value, element, param) {
            var result = false;
            var useId = param;
            if (!useId) {
                useId = 0;
            }
            // 设置同步
            $.ajaxSetup({
                async: false
            });
            $.get(baseURL + "user/" + useId + "/" + value + "/checkMobileExist", function (data) {
                if (typeof data == "string") {
                    if (data == "true") {
                        data = true;
                    } else {
                        data = false;
                    }
                }
                result = !data;

            });
            // 恢复异步
            $.ajaxSetup({
                async: true
            });
            return result;
        }, "手机号码已存在");
    } else {
        console.log("jquery.validate自定义公共验证方法没有生效，如需使用请在base.js前面引用jquery.validate相关js和css");
    }

}(jQuery));


//区域联动,$area：区域选择框jquery对象，pAreaCode:父区域id
function reloadAreaByPAreaCode($area, pAreaCode) {
    var html_ = '<option value="">请选择</option>';
    // 清空选择框所有下级选择框的内容
    $area.nextAll().each(function () {
        if (!$(this).attr("areaCode")) {
            $(this).html(html_).hide();
        }
    });
    if (pAreaCode === "" || pAreaCode === null || pAreaCode === undefined) {
        $area.html(html_).hide();
        return;
    } else {
        $area.show();
    }
    $.ajax({
        url: baseURL + "area/next_areas/short/" + pAreaCode,
        data: {},
        type: "get",
        cache: false,
        dataType: "json",
        async: true, //默认为true 异步
        success: function (data) {
            data = JSON.parse(data);
            $.each(data, function (index, item) {
                html_ += '<option value="' + item.areaCode + '">' + item.name + '</option>';
            });
            $area.html(html_);
            if ($area.attr("areaCode")) {
                $area.val($area.attr("areaCode"));
                $area.change();
            }
        }
    });
}

//区域联动,$area：区域选择框jquery对象，$parea:父区域选择框jquery对象
function reloadAreaByPArea($area, $parea) {
    if ($parea) {
        $parea.change(function () {
            reloadAreaByPAreaCode($area, this.value);
        });
    } else {
        reloadAreaByPAreaCode($area, 0);
    }
}

/**
 * Luhn算法校验规则：16位银行卡号（19位通用）:
 * 1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以 2。
 * 2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
 * 3.将加法和加上校验位能被 10 整除。
 * author shuliangxing 2017-5-9 10:47:12
 * @param bankno
 * @returns {Boolean}
 */
function checkBankCardLuhn(bankno) {
    var num = /^\d*$/; //全数字
    if (!num.exec(bankno)) {
        //top.layer.msg("银行卡号必须全为数字");
        return "银行卡号必须全为数字";
    }
    if (bankno.length < 16 || bankno.length > 19) {
        //top.layer.msg("银行卡号长度必须在16到19之间");
        return "银行卡号长度必须在16到19之间";
    }
    //开头6位
    var strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
    if (strBin.indexOf(bankno.substring(0, 2)) == -1) {
        //top.layer.msg("银行卡号开头2位不符合规范");
        return "银行卡号开头2位不符合规范";
    }
    var lastNum = bankno.substr(bankno.length - 1, 1);//取出最后一位（与luhm进行比较）

    var first15Num = bankno.substr(0, bankno.length - 1);//前15或18位
    var newArr = new Array();
    for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
        newArr.push(first15Num.substr(i, 1));
    }
    var arrJiShu = new Array(); //奇数位*2的积 <9
    var arrJiShu2 = new Array(); //奇数位*2的积 >9

    var arrOuShu = new Array(); //偶数位数组
    for (var j = 0; j < newArr.length; j++) {
        if ((j + 1) % 2 == 1) {//奇数位
            if (parseInt(newArr[j]) * 2 < 9) {
                arrJiShu.push(parseInt(newArr[j]) * 2);
            } else {
                arrJiShu2.push(parseInt(newArr[j]) * 2);
            }
        } else {//偶数位
            arrOuShu.push(newArr[j]);
        }

    }

    var jishu_child1 = new Array();//奇数位*2 >9 的分割之后的数组个位数
    var jishu_child2 = new Array();//奇数位*2 >9 的分割之后的数组十位数
    for (var h = 0; h < arrJiShu2.length; h++) {
        jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
        jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
    }

    var sumJiShu = 0; //奇数位*2 < 9 的数组之和
    var sumOuShu = 0; //偶数位数组之和
    var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
    var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
    var sumTotal = 0;
    for (var m = 0; m < arrJiShu.length; m++) {
        sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
    }

    for (var n = 0; n < arrOuShu.length; n++) {
        sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
    }

    for (var p = 0; p < jishu_child1.length; p++) {
        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
    }
    //计算总和
    sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu)
        + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

    //计算Luhm值
    var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
    var luhm = 10 - k;

    if (lastNum == luhm) {
        return true;
    } else {
        //top.layer.msg("银行卡号错误，请仔细检查");
        return "银行卡号错误，请仔细检查";
    }
};

function getAreaList(pAreaCode) {

    if (typeof(pAreaCode) == "undefined") {
        return;
    }

    var areaObj = null;
    $.ajax({
        url: baseURL + "area/next_areas/short/" + pAreaCode,
        data: {},
        type: "get",
        cache: false,
        dataType: "json",
        async: false, //默认为true 异步
        success: function (r) {
            areaObj = JSON.parse(r);
        }
    });
    return areaObj;
};


function getBankList(cardProvince, cardCity, cardDistrict, cardNum) {
    var bankObj = null;
    $.ajax({
        type: 'POST',
        url: baseURL + "bank/selectByProviceAndCity",
        data: {"provinceCode": cardProvince, "cityCode": cardCity, "countyCode": cardDistrict, "bankCardNo": cardNum},
        dataType: 'json',
        async: false, //默认为true 异步
        success: function (data) {
            bankObj = data;
        }
    });
    return bankObj;
};

function getBranchBankObj(id) {
    var bankObj = null;
    $.ajax({
        type: 'POST',
        url: baseURL + "bank/selectById",
        data: {"id": id},
        dataType: 'json',
        async: false, //默认为true 异步
        success: function (data) {
            if (data.code == 500) {
                bankObj = {};
            } else {
                bankObj = data.result;
            }
        }
    });
    return bankObj;
};




